<script setup lang="ts">
import { dayjs, type TabPaneName } from 'element-plus'
import { useLoadData, type ListItem } from './composable'

import ReportComponent from './components/ReportComponent.vue'
import { REPORT_FORM_ID, REPORT_ID } from '@/enum'

const month = ref(dayjs().subtract(1, 'month').format('YYYY-MM'))
const visible = ref(false)
const componentRef = ref<any>()

const {
  loading,
  tableData,
  queryList,
  exportFile,
} = useLoadData()

const currentRow = ref<ListItem>()
const title = computed(() => {
  return `${unref(currentRow)?.reportName ?? ''}`
})

// 默认不展示保存按钮，只有是修改入口进入成本表时才展示
const showSaveButton = ref(false)

// 成本表只读控制
const readonly = ref(false)
const forceShowTab = ref(false)

// 查看只读情况下显示导出按钮
const showExportButton = computed(() => {
  return unref(readonly)
})

// 是否显示修改入口按钮
function showEditButton(row: ListItem) {
  return row.reportId === REPORT_ID.ELECTRICITY_BILL_SUMMARY
}

async function clickView(row: ListItem) {
  currentRow.value = row
  readonly.value = true
  forceShowTab.value = false
  showSaveButton.value = false
  await nextTick()
  visible.value = true
}

async function clickEdit(row: ListItem) {
  currentRow.value = row
  readonly.value = false
  // 强制显示成本表
  forceShowTab.value = true
  showSaveButton.value = true
  await nextTick()
  visible.value = true
}

async function whenTabChange(name: TabPaneName) {
  // 在修改模式下，成本表显示保存按钮，其他不显示
  // 查看模式下都不显示保存按钮
  showSaveButton.value = unref(readonly) ? false : name === REPORT_FORM_ID.ELECTRICITY_BILL_SUMMARY_2
}

async function clickBack() {
  visible.value = false
  currentRow.value = undefined
  await nextTick()
  clickSearch()
}
async function clickSearch() {
  if (!unref(month)) {
    ElMessage.warning('请选择报告期')
    return
  }
  queryList({
    time: unref(month),
  })
}

// 电量电费汇总表-成本表是需要保存的
async function clickSave() {
  if (showSaveButton.value && componentRef.value) {
    componentRef.value.getDataFromSummaryCompanyElectricity?.()
  }
}

async function clickExport(row?: ListItem) {
  if (row && row.reportId) {
    exportFile(unref(month), row.reportId)
  }
  else {
    const c = unref(currentRow)
    if (c && c.reportId) {
      exportFile(unref(month), c.reportId)
    }
  }
}

function whenTabBeforeLeave(saveFn: () => Promise<boolean>) {
  return new Promise<any>((resolve, reject) => {
    saveFn().then((res) => {
      resolve(res)
    }).catch((e) => {
      reject(e)
    })
  })
}

onMounted(() => {
  clickSearch()
})
</script>

<template>
  <div class="h-full w-full flex flex-col p-4">
    <div class="fs-14 flex items-center gap-3">
      <span>报告期：</span>
      <ElDatePicker v-model="month" :clearable="false" :editable="false" type="month" placeholder="请选择月份" value-format="YYYY-MM" format="YYYY-MM" />
      <SearchButton @click="clickSearch" />
    </div>
    <ElTable
      v-loading="loading" :data="tableData"
      height="100%" class="alpha-block mt-4 !border-0"
      element-loading-custom-class="global-loading"
    >
      <template #empty>
        <TableEmpty />
      </template>
      <ElTableColumn label="报表名称" prop="reportName" />
      <ElTableColumn label="操作" :width="240">
        <template #default="scope">
          <ElButton
            type="primary"
            size="small"
            @click="clickView(scope.row)"
          >
            查看
          </ElButton>
          <ElButton
            v-if="showEditButton(scope.row)"
            type="danger"
            size="small"
            @click="clickEdit(scope.row)"
          >
            修改
          </ElButton>
          <ElButton
            type="success"
            size="small"
            @click="clickExport(scope.row)"
          >
            导出
          </ElButton>
        </template>
      </ElTableColumn>
    </ElTable>
    <FullscreenModal v-model="visible">
      <div v-if="visible" class="absolute inset-0 m-4 flex flex-col gap-4">
        <ElPageHeader class="flex-shrink-0 px-4 py-3" title="返回" :content="currentRow?.reportName" @back="clickBack" />
        <ReportComponent v-if="currentRow" ref="componentRef" :force-show-tab="forceShowTab" :readonly="readonly" :month="month" :title="title" :report-id="currentRow.reportId" :when-tab-before-leave="whenTabBeforeLeave" @tab-change="whenTabChange">
          <template #action>
            <div class="absolute right-0 top-1/2 flex items-center -translate-y-1/1">
              <ElButton v-if="showSaveButton" type="primary" @click="clickSave">
                保存
              </ElButton>
              <ElButton v-if="showExportButton" type="success" @click="clickExport()">
                导出
              </ElButton>
            </div>
          </template>
        </ReportComponent>
      </div>
    </FullscreenModal>
  </div>
</template>
